package com.cn.algorithm.two.line;

import java.util.Arrays;

public class RadixSort {

    public static void main(String[] args) {
        int[] arr = {99, 7, 400, 2, 532, 3, 8};
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }


    public static void sort(int[] arr) {
        if (arr == null || arr.length == 0) {
            return;
        }
        int max = arr[0];
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > max ) {
                max = arr[i];
            }
        }
        for (int i = 1; max / i > 0; i *= 10) {
            radix(arr, i);
        }
    }

    public static void radix(int[] arr, int tmp) {
        int[] bucket = new int[10];
        for (int i = 0; i < arr.length; i++) {
            bucket[arr[i] / tmp % 10]++;
        }
        for (int i = 1; i < bucket.length; i++) {
            bucket[i] += bucket[i - 1];
        }
        int[] newArray = new int[arr.length];
        for (int i = arr.length - 1; i >= 0; i--) {
            newArray[bucket[arr[i] / tmp % 10] - 1] = arr[i];
            bucket[arr[i] / tmp % 10]--;
        }
        for (int i = 0; i < newArray.length; i++) {
            arr[i] = newArray[i];
        }
    }
}
